import * as bf from 'node:buffer';
import { createRequire } from 'node:module';

import { UPLOAD_PATH,readFileBySuffixName } from '../../utils/index.mjs';

const require = createRequire(import.meta.url);
const fs = require('node:fs');
const path = require('node:path');

const multer = require('multer');

const upload = multer({ dest: UPLOAD_PATH });

export function createFileHandler(app, logger) {
  // =================文件 Begin============================
  // 打开视频
  app.get('/video', (req, res) => {
    const range = req.headers.range;
    if (!range) {
      res.status(400).send('Requires Range header');
    }
    const videoPath = req.query.path;
    try {
      // 判断文件是否存在
      fs.existsSync(videoPath, (error) => {
        if (error) {
          console.log(`${decodeURI(videoPath)}文件不存在！`);
          // 文件不存在，向客户端发送404状态码，并发送该文件不存在的字符串
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.send({ code: 400, msg: `${videoPath}文件不存在！` });
          res.end();
        }
      });

      // 使用router模块的函数
      readFileBySuffixName(videoPath, fs, req, res);
    } catch (error) {
      logger.info(error);
      res.send({ code: 500, msg: '打开视频失败' });
      res.end();
    }
  });

  // 打开加载文件
  app.get('/file/load', (req, res) => {
    const filePath = req.query.path;
    if (!filePath) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    try {
      // 判断文件是否存在
      fs.existsSync(filePath, (error) => {
        if (error) {
          logger.info(`${decodeURI(filePath)}文件不存在！`);
          // 文件不存在，向客户端发送404状态码，并发送该文件不存在的字符串
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.send({ code: 400, msg: `${filePath}文件不存在！` });
          res.end();
        }
      });

      // 使用router模块的函数
      readFileBySuffixName(filePath, fs, req, res);
    } catch (error) {
      logger.info(error);
      res.send({ code: 500, msg: '打开文件失败' });
      res.end();
    }
  });

  // 检测文件是否存在
  app.get('/file/check', (req, res) => {
    const filePath = req.query.path;
    if (!filePath) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    try {
      // 判断文件是否存在
      const exists = fs.existsSync(filePath, (error) => {
        if (error) {
          console.log(`${decodeURI(filePath)}文件不存在！`);
          res.send({ code: 200, data: false, msg: `${filePath}文件不存在！` });
          res.end();
        }
      });
      res.send({
        code: 200,
        data: exists,
        msg: exists ? '文件存在' : '文件不存在',
      });
      res.end();
    } catch (error) {
      logger.info(error);
      res.send({ code: 500, msg: '文件检测失败' });
      res.end();
    }
  });

  // 保存设计文件
  app.post('/file/save', (req, res) => {
    const action = req.query.action;
    if (!action) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    let result = { code: 200, msg: '保存成功' };
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', async () => {
      try {
        data = JSON.parse(data); // 将JSON字符串解析成对象
        const { content, savePath } = data;
        let finalPath = savePath;
        // overwrite为覆盖保存，rename为重命名保存
        if (action === 'rename') {
          const ext = path.extname(savePath);
          const target = path.dirname(savePath);
          const newName = path.basename(savePath, ext);
          const newPath = path.resolve(target, newName);
          finalPath = newPath + ext;
          let count = 0;
          while (fs.existsSync(finalPath)) {
            count++;
            finalPath = `${newPath} (${count})${ext}`;
          }
        }
        fs.writeFileSync(finalPath, content);
        result = {
          code: 200,
          data: { fileName: path.basename(finalPath), fullPath: finalPath },
          msg: `保存成功, 文件路径为：${finalPath}`,
        };
      } catch (error) {
        logger.info(error);
        result = { code: 500, msg: '保存失败' };
      } finally {
        res.send(result);
      }
    });
  });

  // 上传文件
  app.post('/file/upload', upload.single('chunk'), (req, res) => {
    const { fileName, index } = req.body;
    const chunkFilePath = path.join(UPLOAD_PATH, `${fileName}-${index}`);
    fs.renameSync(req.file.path, chunkFilePath);
    // 合并文件
    const chunkCount = Math.ceil(req.file.size / (2 * 1024 * 1024));
    const chunks = [];
    for (let i = 0; i < chunkCount; i++) {
      chunks.push(fs.readFileSync(path.join(UPLOAD_PATH, `${fileName}-${i}`)));
    }
    fs.writeFileSync(
      path.join(UPLOAD_PATH, fileName),
      bf.Buffer.concat(chunks),
    );
    res.json({ index, message: '上传成功' });
  });
  // 切片
  app.get('/file/uploaded-chunks', (req, res) => {
    const { fileName } = req.query;
    const uploadedChunks = [];

    fs.readdirSync(UPLOAD_PATH).forEach((file) => {
      const match = file.match(new RegExp(`${fileName}-(\\d+)`));
      if (match) {
        uploadedChunks.push(Number(match[1]));
      }
    });
    res.json(uploadedChunks);
  });
  // 检查文件
  app.get('/file/check-file', (req, res) => {
    const { hash } = req.query;
    const filePath = path.join(UPLOAD_PATH, hash);
    const exists = fs.existsSync(filePath);
    res.json({ exists });
  });

  // =================文件 End============================
}
